package com.whu.administrator.ws;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.orm.SugarApp;
import com.orm.SugarRecord;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;

import chat.network.tcp.PushService;
import mine.activity.MyActivity;
import mine.broadcast.AlarmReceiver;
import model.BeiWang;
import model.OwnUser;
import utils.TimeUtil;

/**
 * Created by Administrator on 2016/2/21.
 */
public class MyApplication extends SugarApp {
    // 应用程序单例，使用Context方便
    public static MyApplication shareApp;

    public static boolean isExitMust  = false;

    public static DisplayImageOptions options;
    static
    {
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.defalut_img) //设置图片在下载期间显示的图片
                .showImageForEmptyUri(R.drawable.defalut_img)//设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.defalut_img)  //设置图片加载/解码过程中错误时候显示的图片
                .cacheInMemory(true)//设置下载的图片是否缓存在内存中
                .cacheOnDisc(true)//设置下载的图片是否缓存在SD卡中
                .considerExifParams(true)  //是否考虑JPEG图像EXIF参数（旋转，翻转）
                .imageScaleType(ImageScaleType.EXACTLY)//设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型//
                .resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位
                .displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少
                .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间
                .build();//构建完成
    }


    // 全局Context获得
    public static MyApplication share() {
        return shareApp;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // 检查错误
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                ex.printStackTrace();
            }
        });
        shareApp = this;
        UIHandler.uiHandler = new UIHandler();

        initdata();

        initImageLoader(getApplicationContext());

    }


    private void initImageLoader(Context context) {
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        config.writeDebugLogs(); // Remove for release app

        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());

    }

    // 初始化推送服务
    private void initPushServise() {
        Intent intent = new Intent(this,PushService.class);
        intent.putExtra(PushService.SERVICE_ACTION, PushService.ACTION_CONNECTION);
        startService(intent);
    }

    private void initdata() {
        if (getOwnUser() == null) return;
        if (getOwnUser().isLogined()) {
            long nowTimem = System.currentTimeMillis();
            // 初始化闹铃
            List<BeiWang> beiWangs = SugarRecord.listAll(BeiWang.class);
            for(BeiWang tmp:beiWangs)
            {
                AlarmManager mAlarm = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
                Intent intent = new Intent(this,
                        AlarmReceiver.class);
                intent.putExtra("id",tmp.getId());
                PendingIntent pendingIntent = PendingIntent.getBroadcast(
                        this, tmp.getId().intValue(), intent, 0);// 第二个参数为区别不同闹铃的唯一标识
                    /* 设置闹钟 */
                String time = tmp.getTime();
                long l = 0;
                try {
                    l = TimeUtil.str2TimeStamp(time);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (l < nowTimem) continue;
                mAlarm.set(AlarmManager.RTC_WAKEUP, l, pendingIntent);
            }

            // 初始化推送服务
            initPushServise();
        }

    }

    public static OwnUser getOwnUser()
    {
        OwnUser ownUser = null;
        {
            List<OwnUser> ownUsers = SugarRecord.listAll(OwnUser.class);
            if (!ownUsers.isEmpty()) {
                ownUser = ownUsers.get(0);
            }
        }
        return ownUser;
    }

}
